/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package axil.stdlib.time.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.Formatting;
import axil.api.Persona;
import axil.stdlib.core.type.Atom;
import axil.stdlib.core.type.Nil;

import java.util.TimeZone;

import static axil.framework.Functions.*;


/**
 * An Axil representation of time. This only understands time of day, not time
 * across days.
 */
public class Time extends Atom implements Temporal {
	public static final AxilType type = Time_Type.object;
	public static final Time midnight = new Time(0, 0);

	private final int hours;
	private final int minutes;


	public Time(int hours, int minutes) {
		this.hours = hours;
		this.minutes = minutes;
	}


	public Time(int hours, int minutes, char meridian) {
		// 12:30am --> 0:30
		// 11:30am --> 11:30
		// 1:00pm --> 13:00
		// 11:45pm --> 23:45
		// 12:15pm --> 12:15

		this.minutes = minutes;
		if (meridian == 'P') {
			this.hours = hours == 12 ? 12 : hours + 12;
		} else {
			if (meridian == 'A') {
				this.hours = hours == 12 ? 0 : hours;
			} else {
				throw abort("Invalid time");
			}
		}
	}


	public static boolean valid(int hour, int minute, int second) {
		return (hour >= 0) && (hour < 24) &&
		       (minute >= 0) && (minute < 60) &&
		       (second >= 0) && (second < 60);
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Return the host application (or built-in Java) object that most closely
	 * matches this value object. Return returned value is never null unless
	 * this value object represents the special 'nil' object.
	 */
	public Object intrinsic() {
		return (hours * 3600) + (minutes * 60);
	}


	/**
	 * Extract from the temporal value the indicated unit. If the unit makes no
	 * sense for the type, then an exception is thrown.
	 */
	public int extract(TimeZone tz, Part part) {
		switch(part) {
		case hour:
			return hours;
		case minute:
			return minutes;
		case second:
			return 0;
		case millisecond:
			return 0;

		default:
			throw error(axil(), "invalid-temporal-part",
			            nv("type", this.type()), nv("part", part.name()));
		}
	}


	/**
	 * Add the given value to this value, returning a new object. The given
	 * value is never null or nil. The value may be a numeric type of any other
	 * type of object that can sensibly implement the Added interface.
	 */
	public AxilObject add(AxilObject object) {
		if (object == Nil.object) {
			return Nil.object;
		}
		if (object instanceof Interval) {
			Interval i = (Interval)object;
			switch(i.span()) {
			case hour:
				int hs = (int)i.magnitude().whole();
				int ms = minutes + (int)(60 * i.magnitude().tenths());
				if (ms > 60) {
					hs = hs + (ms / 60);
				}
				hs = rollover(hours + hs, 24);
				return new Time(hs, ms);

			case minute:
				int m = minutes + (int)i.magnitude().whole();
				int h = m / 60;
				if (h > 0) {
					m = m % 60;
				}
				h = rollover(hours + h, 24);
				return new Time(h, m);

			default:
				/*
				 * In this case, the interval is either too large or too
				 * small to have a material impact on the time. So, we
				 * simply return this object.
				 */
				return this;
			}
		}
		throw error(axil(), "expecting-time-add", nv("actual", object.type()));
	}


	/**
	 * Subtract the given object from this object. The given value is never
	 * null or nil. The value may be a numeric type of any other type of object
	 * that can sensibly implement the Subtracted interface.
	 */
	public AxilObject subtract(AxilObject object) {
		if (object == Nil.object) {
			return Nil.object;
		}
		if (object instanceof Interval) {
			Interval i = (Interval)object;
			switch(i.span()) {
			case hour:
				int hs = (int)i.magnitude().whole();
				int ms = Math.abs(minutes - (int)(60 * i.magnitude().tenths()));
				if (ms > 60) {
					hs = hs + (ms / 60);
				}
				hs = rollover(Math.abs(hours - hs), 24);
				return new Time(hs, ms);

			case minute:
				int m = Math.abs(minutes - (int)i.magnitude().whole());
				int h = m / 60;
				if (h > 0) {
					m = m % 60;
				}
				h = rollover(Math.abs(hours - h), 24);
				return new Time(h, m);

			default:
				/*
				 * In this case, the interval is either too large or too
				 * small to have a material impact on the time. So, we
				 * simply return this object.
				 */
				return this;
			}
		}
		throw error(axil(), "expecting-time-subtract", nv("actual", object.type()));
	}


	private int rollover(int i, int span) {
		if (i >= span) {
			i = i - span;
		}
		return i;
	}


	/**
	 * Returns a hash code value for the object. All Axil values must provide a
	 * meaningful implementation of this function to enable themselves to be
	 * placed in a map or set.
	 */
	protected int hash() {
		return hours + minutes;
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		if (object instanceof Time) {
			Time t = (Time)object;
			return (hours == t.hours) && (minutes == t.minutes);
		}
        if (object instanceof Timestamp) {
            Time other = ((Timestamp)object).time(persona().timezone());
            return this.equalTo(other);
        }
		return false;
	}


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, a ClassCastException may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
	public int comparedTo(AxilObject object) {
        if (object instanceof Time) {
            Time other = (Time)object;
            int d = this.hours - other.hours;
            if (d == 0) {
                d = this.minutes - other.minutes;
            }
            return d;
        }
        if (object instanceof Timestamp) {
            Time other = ((Timestamp)object).time(persona().timezone());
            return this.compareTo(other);
        }
        // "nil" comparison; always return 1 (nil less than everything).
        if (object == Nil.object) {
            return 1;
        }
        // Incorrect comparison.
        throw error(axil(), "order-comparison",
                nv("this", this.type()),
                nv("that", object.type()));
    }


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		// TODO: Put proper formatting back in
		String h = str(hours);
		String m = str(minutes);
		return h + ':' + m;
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		String h = str(hours);
		String m = str(minutes);
		return h + ':' + m;
	}
}
